package org.example.controller;

import jakarta.validation.constraints.Pattern;
import org.example.pojo.Patient.PatientUser;
import org.example.pojo.Result;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.JwtUtil;
import org.example.utils.Md5Util;
import org.example.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.example.pojo.DoctorUser;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password, String role){
        //查询用户，如果存在则不允许再注册
        //从Service服务中调用方法查询
        User u = userService.findByUserName(username);
        String nickname;
        // 根据角色设置昵称
        if (role == null) {
            role = "0";
        }
        switch (role) {
            case "0":
                nickname = "患者";
                break;
            case "2":
                nickname = "医生";
                break;
            default:
                nickname = "未知角色";
                break;
        }
        //判断用户是否存在
        if (u==null){
            //如果不存在则进行注册
            userService.register(username,password,role,nickname);
            return Result.success();
        }else {
            //返回错误信息
            return Result.error("用户已存在！");
        }
    }
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        // 创建基础日志信息
        Map<String, Object> logData = new HashMap<>();
        logData.put("username", username);
        logData.put("loginTime", LocalDateTime.now().toString());
        
        User loginUser = userService.findByUserName(username);
        if (loginUser == null){
            // 记录用户不存在的失败日志
            logData.put("status", "failed");
            logData.put("reason", "用户不存在");
            logger.warn("登录失败: {}", JSON.toJSONString(logData));
            return Result.error("用户不存在");
        }
        
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            
            //把token存在redis中实现旧token的删除
            ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,12, TimeUnit.HOURS);
            
            // 记录登录成功日志
            logData.put("status", "success");
            logData.put("userId", loginUser.getId());
            logData.put("role", loginUser.getRole());
            logData.put("nickname", loginUser.getNickname());
            logData.put("email", loginUser.getEmail());
            logData.put("createTime", loginUser.getCreateTime());
            logger.info("登录成功: {}", JSON.toJSONString(logData));
            
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("user", loginUser);
            responseData.put("token", token);
            responseData.put("loginLog", logData);
            
            return Result.success(responseData);
        }
        
        // 记录密码错误的失败日志
        logData.put("status", "failed");
        logData.put("reason", "密码错误");
        logger.warn("登录失败: {}", JSON.toJSONString(logData));
        return Result.error("密码错误");
    }
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/){
       /* Map<String,Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");//此处的.get("username")为解析token中map集合（"username"：)中的内容*/
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd)||!StringUtils.hasLength(newPwd)||!StringUtils.hasLength(rePwd)){
            return Result.error("缺少参数");
        }
        //校验oldPwd是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码错误");
        }
        //比对newPwd与rePwd
        if (!rePwd.equals(newPwd)){
            return Result.error("两次填写的新密码不一样");
        }
        //调用Service
        userService.updatePwd(newPwd);
        ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
